﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    public class WaitLoadGameObjectCache : CustomYieldInstruction
    {
        private GameObjectCache cache;
        private GameObject obj;
        private InstantiateQueue queue;
        private int prority;
        private bool isLoaded;
        public string Error { get; set; }

        public WaitLoadGameObjectCache(GameObjectCache cache, InstantiateQueue instantiateQueue, int instantiatePriority)
        {
            this.cache = cache;
            this.queue = instantiateQueue;
            this.prority = instantiatePriority;
        }
        ~WaitLoadGameObjectCache()
        {
            this.cache.Loading = false;
        }

        public GameObject GetObject()
        {
            if (!this.cache.IsNotNull())
            {
                return null;
            }

            if(this.queue == null && this.obj == null)
            {
                this.obj = this.cache.PoolGet(null);
            }
            this.cache.Loading = false;
            return this.obj;
        }

        public override bool keepWaiting
        {
            get
            {
                if (!string.IsNullOrEmpty(this.cache.Error))
                {
                    this.cache.Loading = false;
                    this.Error = this.cache.Error;
                    return false;
                }
                if (!this.cache.IsNotNull())
                {
                    return true;
                }

                if(this.queue != null)
                {
                    if (!this.isLoaded)
                    {
                        this.isLoaded = true;
                        this.cache.LoadObject(this.queue, this.prority, (go) => { this.obj = go; });
                    }
                    if (this.obj == null) return true;
                }
                return false;
            }
        }
    }
}